#include "SystemImageList.h"
#include <assert.h>
#include <shellapi.h>


CSystemImageList::CSystemImageList(void) {
	m_imageList = NULL;

	m_hInstShell32 = ::LoadLibrary(_T("shell32.dll"));
	assert (m_hInstShell32 != NULL);

	m_procShellGetImageLists = (ShellGetImageListsProc)::GetProcAddress(m_hInstShell32, (LPCSTR)71);
	assert (m_procShellGetImageLists != NULL);

	m_procFileIconInit = (FileIconInitProc)::GetProcAddress(m_hInstShell32, (LPCSTR)660);
	assert (m_procFileIconInit != NULL);
}

CSystemImageList::~CSystemImageList(void) {
	if (m_hInstShell32 != NULL) {
		FreeLibrary(m_hInstShell32);
		m_hInstShell32 = NULL;
	}
}

HIMAGELIST CSystemImageList::getImageList() {
	assert (m_imageList != NULL);
	return m_imageList;
}

bool CSystemImageList::load() {
	if (!m_procShellGetImageLists) {
		return false;
	}

	HIMAGELIST big;
	if (m_procShellGetImageLists(&big, &m_imageList)) {
		return true;
	}

	return false;
}

int CSystemImageList::getIconIndexByExt(const tstring &ext) {

	tstring file = _T("c:\\1.");
	file += ext;

	return getIconIndexByName(file);
}

int CSystemImageList::getIconIndexByName(const tstring &pathname) {
	SHFILEINFO sfi;
	memset (&sfi, 0, sizeof(sfi));
	DWORD_PTR ret = SHGetFileInfo(pathname.c_str(),
	                              FILE_ATTRIBUTE_NORMAL,
	                              &sfi, sizeof(sfi),
	                              SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX
	                             );
	if (ret == NULL) {
		return -1;
	} else {
		return sfi.iIcon;
	}
}